package com.wondertek.service.service.business.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wondertek.common.base.Result;
import com.wondertek.service.dto.business.req.IpcAccessorySaveReq;
import com.wondertek.service.entity.business.DevicePo;
import com.wondertek.service.entity.business.IpcAccessoryPo;
import com.wondertek.service.mapper.business.IpcAccessoryMapper;
import com.wondertek.service.sdk.iotdh.dto.req.StreamUrlAddDhReq;
import com.wondertek.service.sdk.iotdh.service.DhDeviceService;
import com.wondertek.service.service.business.DeviceService;
import com.wondertek.service.service.business.IpcAccessoryService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description: ipc配件关系
 * @author: qinjianhui
 * @create: 2024-08-28 13:43
 **/
@Service
public class IpcAccessoryServiceImpl extends ServiceImpl<IpcAccessoryMapper,IpcAccessoryPo> implements IpcAccessoryService {

    @Resource
    private DeviceService deviceService;

    @Resource
    private DhDeviceService dhDeviceService;

    /*
    * 新增
    * */
    @Override
    public void save(IpcAccessorySaveReq req){
        IpcAccessoryPo ipcAccessoryPo = new IpcAccessoryPo();
        BeanUtil.copyProperties(req, ipcAccessoryPo);
        ipcAccessoryPo.setIsDelete(0);
        this.save(ipcAccessoryPo);
    }

    /*
    * 根据配件sn码获取视频流
    * */
    public String getStreamUrlByAccessory(String snCode,String startTime,String endTime,String businessType){
        //根据配件sncode获取ipc信息
        LambdaQueryWrapper<IpcAccessoryPo> ipcAccessoryPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ipcAccessoryPoLambdaQueryWrapper.eq(IpcAccessoryPo::getAccessorySn,snCode);
        ipcAccessoryPoLambdaQueryWrapper.orderByDesc(IpcAccessoryPo::getCreateTime);
        List<IpcAccessoryPo> list = this.list(ipcAccessoryPoLambdaQueryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            IpcAccessoryPo ipcAccessoryPo = list.get(0);
            //再去查ipc信息
            DevicePo devicePo = deviceService.getById(ipcAccessoryPo.getIpcId());
            if(devicePo!=null){
                //获取视频流
                StreamUrlAddDhReq req = new StreamUrlAddDhReq();
                req.setBeginTime(startTime);
                req.setEndTime(endTime);
                req.setDeviceSn(devicePo.getSnCode());
                req.setDeviceId(devicePo.getDeviceCode());
                req.setDeviceSk(devicePo.getSkCode());
                req.setChannelId("0");
                req.setProtoType("rtsp");
                req.setBusinessType(businessType);
                Result<String> result = dhDeviceService.addStreamUrl(req);
                return result.getData();
            }
        }
        return null;
    }
}

